package org.itboys.core.service.mongo.front;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.image.ImageUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.core.dto.member.SundayMemberSessionDto;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.util.NumberUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_用户_service_微信
 */
@Service
public class SundaySmallMemberService extends BaseMongoService<SundayMember> {
    @Autowired
    private SundayValicodedateService codeService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundaySmallUserInfoService infoService;
    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }

    /**
     * 微信用户修改资料
     * @param memberId
     * @param nickName
     * @param sex
     * @param mobile
     */
    public SundayMember updateMember(Long memberId,String nickName,String image,String sex,String mobile,String validateCode){
        SundayMember member=super.getById(memberId);
        if(StringUtils.isNotBlank(nickName)){
            member.setNickName(nickName);
        }
        if(StringUtils.isNotBlank(sex)){
            member.setSex(sex);
        }
        if(StringUtils.isNotBlank(mobile)){
            Map<String,Object> param=new HashMap<String,Object>();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("mobile",mobile);
            if(ListUtil.isNotNull(super.list(param))){
                throw new ErrorException("手机号已被使用");
            }
            codeService.checkValidateCode(mobile,validateCode);
            member.setMobile(mobile);
        }
        if(StringUtils.isNotBlank(image)){
            //保存微信头像
            String random= NumberUtil.generateNumber("FRESH");
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/wxlogo/"+random+".jpg";
            ImageUtils.buildImg(savePath,image);
            //头像半链接
            member.setImage("/wxlogo/"+random+".jpg");
        }
       super.updateExceptEmpty(memberId,member);
        return member;
    }

    /**
     * 小程序首次登录
     * @param memberId
     * @param code
     * @param encryptedData
     * @param iv
     * @param mobile
     * @param validateCode
     * @return
     * @throws Exception
     */
    public SundayMember loginWithUnion(Long memberId,String code,String encryptedData,String iv,String mobile,String validateCode) throws Exception {
        SundayMember member=super.getById(memberId);
        String info=infoService.getUserInfo(code,encryptedData,iv);
        JSONObject userInfoJSON= (JSONObject) JSONObject.parse(info);
        String nickName=String.valueOf(userInfoJSON.get("nickName"));
        String wxLogo=String.valueOf(userInfoJSON.get("avatarUrl"));
        String openId=String.valueOf(userInfoJSON.get("openId"));
        String unionId=String.valueOf(userInfoJSON.get("unionId"));
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
        //先判断是否存在用户
        param.put("weixinUnionId",unionId);
        List<SundayMember> oldMembers=super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            SundayMember oldMember=oldMembers.get(0);
            if(oldMember.getId()!=memberId.longValue()){
                oldMember.setIsLogin(SundayCommonConstants.YES);
                oldMember.setMiniOpenId(openId);
                super.updateExceptEmpty(oldMember.getId(),oldMember);
                //删除新增用户  保留旧用户
                super.delete(memberId);
            }
            return oldMember;
        }
        //保存微信头像
        String random= NumberUtil.generateNumber("FRESH");
        String savePath = resourceHolder.getStringValue("fileUploadPath")+"/wxlogo/"+random+".jpg";
        ImageUtils.buildImg(savePath,wxLogo);
        //头像半链接
        member.setImage("/wxlogo/"+random+".jpg");
        member.setWeixinUnionId(unionId);
        member.setIsLogin(SundayCommonConstants.YES);
        member.setNickName(nickName);
        super.updateExceptEmpty(memberId,member);
        return member;
    }

    public SundayMember loginWithCode(String code) throws IOException {
        String openId=infoService.getOpenId(code);
        return getBySmallOpenId(openId);
    }
    /**
     * 处理来至小程序的用户信息。
     * @param openId
     */
    public SundayMember getBySmallOpenId(String openId){
        SundayMember member=null;
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
       //使用openId标识用户。小程序
        param.put("miniOpenId",openId);
        List<SundayMember> oldMembers=super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            member=oldMembers.get(0);
        }else {
            member=new SundayMember();
            member.setMiniOpenId(openId);
            member.setIsLogin(SundayCommonConstants.NO);
            member.setUserType(SundayCommonConstants.user_type_member);
            super.save(member);
        }
        return member;
    }

    /**
     * 处理来至公众号的用户信息。使用unionId判断标识
     * @param unionId
     * @param openId
     * @param nickName
     * @param wxLogo
     */
    public SundayMemberSessionDto handleMemberInfo(String unionId,
                                                   String openId,
                                                   String nickName,
                                                   String wxLogo,
                                                   Long recommendId){
        SundayMember member=null;
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
        //使用UnionId标识用户。服务号
        param.put("weixinUnionId",unionId);
        List<SundayMember> oldMembers=super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            member=oldMembers.get(0);
            if(StringUtils.isBlank(member.getFuwuOpenId())){
                member.setFuwuOpenId(openId);
                super.updateExceptEmpty(member.getId(),member);
            }
        }else {
            member=new SundayMember();
            member.setNickName(nickName);
            member.setWeixinUnionId(unionId);
            member.setFuwuOpenId(openId);
            member.setIsLogin(0);
            member.setUserType(SundayCommonConstants.user_type_member);
            //保存微信头像
            String random= NumberUtil.generateNumber("FRESH");
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/wxlogo/"+random+".jpg";
            ImageUtils.buildImg(savePath,wxLogo);
            //头像半链接
            member.setImage("/wxlogo/"+random+".jpg");
            super.save(member);
        }
        SundayMemberSessionDto memberDto= new SundayMemberSessionDto(member.getId(),member.getWeixinUnionId(),member.getFuwuOpenId());
        logger.info("------处理来至微信请求-返回用户的ID为-----"+memberDto.getId());
        return memberDto;
    }

    /**
     * 通过weixinopenIdId查询用户
     * @param openId
     * @return
     */
    public SundayMemberSessionDto checkOpenId(String openId){
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
        param.put("fuwuOpenId",openId);
        List<SundayMember> members = super.list(param);
        if(ListUtil.isNull(members))return null;
        SundayMember  member = members.get(0);
        return new SundayMemberSessionDto(member.getId(), member.getWeixinUnionId(), member.getMiniOpenId());
    }

    /**
     * 将用户转换DTO保存到sesssion中。微信专用
     * @param request
     * @param memberId
     * @param memberSessionDto
     */
    public void insertMemberToSession(HttpServletRequest request, Long memberId, SundayMemberSessionDto memberSessionDto){
        SundayMember member = null;
        if(LongUtil.isNotNull(memberId)){
            member=super.getById(memberId);
            memberSessionDto=new SundayMemberSessionDto(member.getId(),member.getWeixinUnionId(), member.getFuwuOpenId());
        }
        logger.info("-----------插入session中的用户信息,openID==="+memberSessionDto.getFuwuOpenId());
        request.getSession().setAttribute("member", memberSessionDto);
    }

}
